package com.longyi.admin.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.longyi.admin.annotation.Logging;
import com.longyi.admin.common.GetPath;
import com.longyi.admin.entity.User;
import com.longyi.admin.service.FileService;
import com.longyi.admin.entity.File;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import com.longyi.admin.common.QueryPageParam;
import com.longyi.admin.common.Result;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * File 前端控制器
 *
 * @author 龙毅
 * @since 2025-09-08
 */
@RestController
@RequestMapping("/file")
public class FileController {

    // 注入service
    @Autowired
    private FileService fileService;
    private final String ip = "http://localhost:8888";

    //获取文件名
    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        if (index > 0) {
            return fileName.substring(0, index);
        } else {
            return "";
        }

    }

    //获取文件后缀名
    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }
        int index = fileName.lastIndexOf(".");
        if (index > 0) {
            return fileName.substring(index + 1);
        } else {
            return "";
        }

    }

    //文件下载
    @GetMapping("/{flag}")
    public void download(@PathVariable String flag, HttpServletResponse response) {
        String filePath = GetPath.getFilePath();
        if (!FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(filePath);
        String targetFileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(targetFileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(targetFileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + targetFileName);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();

            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
    //文件上传
    @PostMapping("/upload")

    public Result upload(@RequestParam("file") MultipartFile file){
        if(file.isEmpty()){
            return Result.fail("文件不能为空");
        }
        String filePath = GetPath.getFilePath();
        if (!FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
        String fileName =getFileName(file.getOriginalFilename()) ;
        String ext=getFileExtension(file.getOriginalFilename());
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(filePath);
        String finalFileName = fileName;
        String targetFileName = fileNames.stream().filter(name -> name.contains(finalFileName)).findAny().orElse("");
        System.out.println(finalFileName);
        String flag = "";
        if (StrUtil.isNotEmpty(targetFileName)) {
            List<File> fileList = fileService.lambdaQuery().eq(File::getName, finalFileName).list();
            if (fileList.size() > 0) {
                for (File file1 : fileList){
                    if (file1.getType().equals( ext)&& file1.getSize().equals(file.getSize())) {
                        return Result.suc(file1);

                    }else{
                        flag=System.currentTimeMillis()+"."+ext;
                    }
                }

            }else{
                flag=fileName+"."+ext;

            }
        }else {
            flag=fileName+"."+ext;

        }
        try {
            FileUtil.writeBytes(file.getBytes(), filePath + flag);
            File file1 = new File();
            file1.setName(fileName);
            file1.setType(ext);
            file1.setSize(file.getSize());
            file1.setUrl(ip+ "/file/" +flag);
            fileService.save(file1);
            return Result.suc(file1);
        }catch (Exception e){
            return Result.fail("上传失败");
        }

    }
    // 统计数量
    @GetMapping("/count")
    public Integer count() {
        return fileService.count();
    }

    // 获取列表
    @GetMapping("/list")
    @Logging(record = "查询文件列表", type = "查询")
    public List<File> list() {
        return fileService.list();
    }

    // 新增数据
    @PostMapping("/save")
    @Logging(record = "新增文件", type = "新增")
    public Result save(@RequestBody File file) {
        return fileService.save(file)
                ? Result.suc("新增成功")
                : Result.fail("新增失败");
    }

    // 修改数据
    @PostMapping("/update")
    @Logging(record = "修改文件", type = "修改")
    public Result update(@RequestBody File file) {
        return fileService.updateById(file)
                ? Result.suc("修改成功")
                : Result.fail("修改失败");
    }

    // 获取详情
    @GetMapping("/info/{id}")
    @Logging(record = "查询文件详情", type = "查询")
    public Result info(@PathVariable("id") Long id) {
        File file = fileService.getById(id);
        return Result.suc(file);
    }
    @PostMapping("/modStatus/{id}")
    public Result modStatus(@PathVariable("id") Long id) {
        File file = fileService.getById(id);
        file.setStatus(file.getStatus()==1?0:1);
        return fileService.updateById(file)?Result.suc("修改成功") : Result.fail("修改失败");
    }
    // 批量删除数据
    @Transactional
    @PostMapping("/deleteBatch")
    @Logging(record = "批量删除文件", type = "删除")
    public Result deleteBatch(@RequestBody Long[] ids) {
        fileService.removeByIds(Arrays.asList(ids));
        return Result.suc("批量删除成功");
    }

    // 分页查询
    @PostMapping("/listPage")
    @Logging(record = "分页查询文件列表", type = "查询")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();

        // 提取查询参数
        String id = (String) param.get("id");
        String name = (String) param.get("name");
        String type = (String) param.get("type");
        String size = (String) param.get("size");
        String url = (String) param.get("url");
        String status = (String) param.get("status");
        String createTime = (String) param.get("createTime");

        // 分页配置
        Page<File> page = new Page<>();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<File> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(id) && !"null".equals(id)) {
            lambdaQueryWrapper.eq(File::getId, id);
        }
        if (StringUtils.isNotBlank(name) && !"null".equals(name)) {
            lambdaQueryWrapper.like(File::getName, name);
        }
        if (StringUtils.isNotBlank(type) && !"null".equals(type)) {
            lambdaQueryWrapper.like(File::getType, type);
        }
        if (StringUtils.isNotBlank(url) && !"null".equals(url)) {
            lambdaQueryWrapper.like(File::getUrl, url);
        }
        if (StringUtils.isNotBlank(status) && !"null".equals(status)) {
            lambdaQueryWrapper.eq(File::getStatus, status);
        }
        if (StringUtils.isNotBlank(createTime) && !"null".equals(createTime)) {
            lambdaQueryWrapper.like(File::getCreateTime, createTime);
        }

        // 执行分页查询
        IPage result = fileService.PageList(page, lambdaQueryWrapper);
        return Result.suc(result.getTotal(), result.getRecords());
    }
}